//
//  WYWTableTool.m
//  SQlite
//
//  Created by Mr.Run on 2017/11/14.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

#import "WYWTableTool.h"
#import "WYWModelTool.h"
#import "WYWSqliteTool.h"

@implementation WYWTableTool

+(NSArray *)tableSortedColumnNames:(Class)cls uid:(NSString *)uid{
    
    NSString *tableName = [WYWModelTool tableName:cls];
    
    /*
    
     CREATE TABLE "WYWStu" (
     "age1" integer,
     "stuNum" integer,
     "score" real,
     "name" text,
     PRIMARY KEY("stuNum")
     )
    
    */
    
    NSString *queryCreateSqlStr = [NSString stringWithFormat:@"select sql from sqlite_master where type = 'table' and name = '%@'", tableName];
    NSMutableDictionary *dic = [WYWSqliteTool querySql:queryCreateSqlStr uid:uid].firstObject;
    NSString *createSqlStr = dic[@"sql"];
    if (createSqlStr.length == 0) {
        return nil;
    }
    
    createSqlStr = [createSqlStr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
    createSqlStr = [createSqlStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    createSqlStr = [createSqlStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    createSqlStr = [createSqlStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    
    NSString *nameTypeStr = [createSqlStr componentsSeparatedByString:@"("][1];
    NSArray *nameTypeArr = [nameTypeStr componentsSeparatedByString:@","];
    NSMutableArray *names = [NSMutableArray array];
    for (NSString *nameType in nameTypeArr) {
        if ([[nameType lowercaseString] containsString:@"primary"]) {
            continue;
        }
        
        NSString *nameType2 = [nameType stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
        
        NSString *name = [nameType2 componentsSeparatedByString:@" "].firstObject;
        [names addObject:name];
    }
    [names sortUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        return [obj1 compare:obj2];
    }];
    return names;
}

+(BOOL)isTableExists:(Class)cls uid:(NSString *)uid{
    NSString *tableName = [WYWModelTool tableName:cls];
    
    NSString *queryCreateSqlStr = [NSString stringWithFormat:@"select sql from sqlite_master where type = 'table' and name = '%@'", tableName];
    NSMutableArray *result = [WYWSqliteTool querySql:queryCreateSqlStr uid:uid];
    
    return result.count > 0;
}

@end
